from __future__ import absolute_import

from file_parser import *
from make_file_base import *

# ------------------------------------------------------------------------------------------------------#

def make_function_body(cls):
  content = '  // ' + cls.get_name() + ' methods.\n'

  flag = False
  funcs = cls.get_virtual_funcs()
  for func in funcs:
    if flag:
      content += '\n\n'
    else:
      flag = True

    content += '  ' + func.get_cpp_proto()
    if cls.is_client_side():
      content += ' override;\n'
    else:
      content += ' override;\n'

  return content

# ------------------------------------------------------------------------------------------------------#

def make_functions_body(cls, header):
  content = make_function_body(cls)

  cur_cls = cls
  while True:
    parent_name = cur_cls.get_parent_name()
    if is_base_class(parent_name):
      break
    else:
      parent_cls = header.get_class(parent_name)
      if parent_cls is None:
        raise Exception('Class does not exist: ' + parent_name)
      if len(content) > 0:
        content += '\n'
      content += make_function_body(parent_cls)

    cur_cls = header.get_class(parent_name)

  return content

# ------------------------------------------------------------------------------------------------------#

def make_ctocpp_header_file(header, dir_path, dir_name, class_name):
  cls = header.get_class(class_name)
  if cls is None:
    raise Exception('Class does not exist: ' + class_name)

  content = get_copyright()
  content += '\n'
  
  content += \
"""
#ifndef $GUARD$
#define $GUARD$
#pragma once
"""
  content += '\n'
  
  # build the function body
  funcs_body = make_functions_body(cls, header)

  # include standard headers
  if funcs_body.find('std::map') > 0 or funcs_body.find('std::multimap') > 0:
    content += '#include <map>\n'
  if funcs_body.find('std::vector') > 0:
    content += '#include <vector>\n'

  result = make_include_file(cls, 'CToCpp', header, dir_name, class_name)
  content += result['content']
  content += '\n'
  
  content += 'namespace OHOS::ArkWeb {\n\n'
  
  content += '// Wrap a C structure with a C++ class.\n'
  content += '// This class may be instantiated and accessed wrapper-side only.\n'
  content += make_class_define(cls, 'CToCpp', result['base_name'], class_name, funcs_body)
  content += '\n'
  
  content += '} // OHOS::ArkWeb\n\n'

  content += \
"""
#endif // $GUARD$
"""

  # add the guard string
  def_name = make_def_file(cls, class_name)
  guard = def_name.upper() + '_CTOCPP_H_'
  content = content.replace('$GUARD$', guard)
  
  absolute_path = os.path.join(dir_path, get_capi_name(class_name, False) + '_ctocpp.h')
  return (content, absolute_path)

